<template>
  <el-button-group>
    <el-button
      :loading="loading"
      :type="btnType"
      @click="handleClick"
      size="mini"
      >{{ $t(label) }}<iframe style="display:none;" ref="iframe"></iframe
    ></el-button>
  </el-button-group>
</template>
<script>
export default {
  name: "l-wordprint-btn",
  props: {
    code: String,
    getFormData: Function,
    label: {
      type: String,
      default: "打印表单",
    },
    btnType: {
      type: String,
      default: "success",
    },
  },
  data() {
    return {
      printTemp: {},
      loading: false,
      timeNum: 1200,
    };
  },
  methods: {
    async handleClick() {
      if (this.loading) {
        return;
      }

      this.lr_loadUsers(this.loginInfo.f_UserId);

      this.timeNum = 1200;
      await this._print();
      this.$emit("click");
    },
    print(html) {
      // 打印表单
      this.write(html);
      setTimeout(() => {
        this.getIframe().window.print();
      }, 100);
    },

    async _print() {
      if (this.$store.state.app.axiosLoadingNum == 0 || this.timeNum == 0) {
        const html = await this.getHtml();
        if (html) {
          this.print(html);
        }
        this.$emit("click");
      } else {
        this.timeNum--;
        setTimeout(async () => {
          await this._print();
        }, 100);
      }
    },

    async getHtml() {
      if (this.code) {
        this.loading = true;
        if (!this.printTemp[this.code]) {
          const api = window.$api.wordPrint.template;
          const apiFile = window.$api.system.annexesFile;
          const tempInfo = await this.$awaitWraper(api.getByCode(this.code));
          if (tempInfo) {
            this.printTemp[this.code] = await this.$awaitWraper(
              apiFile.getHtml(tempInfo.f_FileId)
            );
          } else {
            this.$message({
              type: "warning",
              message: "找不到打印模版!",
            });
            this.loading = false;
            return "";
          }
        }
        const res = await this.setFormData();
        this.loading = false;
        return res;
      }
      return "";
    },
    getIframe() {
      const iframe = this.$refs.iframe;
      return iframe.contentWindow ? iframe.contentWindow : iframe;
    },
    getIframeDoc() {
      const iframe = this.$refs.iframe;
      return iframe.contentWindow.document
        ? iframe.contentWindow.document
        : iframe.contentDocument;
    },
    write(html) {
      html = html
        .replace(/{learun_img_api}/g, `${this.apiUrl}system/annexesfile/`)
        .replace(/{learun_img_token}/g, `token=${this.token}`); // 编辑图片显示

      const doc = this.getIframeDoc();
      doc.open();
      doc.write(
        html.replace(
          /&#x200e;/g,
          '<div style="page-break-after:always;"></div>'
        ) +
          ' <style media="print"> @page { size: auto; margin: 0 20mm;} </style>'
      );
      doc.close();
    },
    getField(html) {
      const map = {};

      let list = html.match(/\$.[^\\$\\$]*\$/g);

      list.forEach((t) => {
        
        let list2 = t.match(/>.[^><]*</g);
        
        if (list2 == null) {
          list2 = t.match(/>.[^><]*\$/g);

          if(list2 == null){
            list2 = t.match(/\$.[^><]*</g);
          } 
          //console.log(t,list2,'getField1')
          if(list2 == null){
            map[t.replace(/\$/g, "")] = map[t.replace(/\$/g, "")] || []
            map[t.replace(/\$/g, "")].push(t.replace(/\$/g, "\\$"))
          } 
        }
        if(list2) {
          let id = "";
          list2.forEach((t2) => {
            id += t2.replace(/>/g, "").replace(/</g, "").replace(/\$/g, "");
          });
          map[id] = map[id] || []
          map[id].push(t.replace(/\$/g, "\\$"))
        }
      });

      return map;
    },
    async getMyFormData() {
      if (this.getFormData) {
        return await this.getFormData();
      } else {
        return {};
      }
    },
    async setFormData() {
      let html = this.printTemp[this.code];
      const fieldMap = this.getField(this.printTemp[this.code]);
      const formData = await this.getMyFormData();

      //console.log(fieldMap,formData,'setFormData');

      for (let key in fieldMap) {
        const value = this.getValue(key, formData);
        for (let i = 0; i < fieldMap[key].length; i++) {
          const reg = new RegExp(fieldMap[key][i], "gim");
          html = html.replace(reg, value);
        }
      }
      return html;
    },
    getValue(path, formData) {
      const paths = path.split(".");
      let data = formData;
      for (let i = 0, len = paths.length; i < len; i++) {
        if (data) {
          data = data[paths[i]];
        }
      }
      if (this.$validatenull(data)) {
        return "";
      }
      return data;
    },
  },
};
</script>
